package com.tdam2014.grupo3.flickr.interfaces;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.tdam2014.grupo3.entities.People;
import com.tdam2014.grupo3.flickr.FlickrException;
import com.tdam2014.grupo3.flickr.Parameter;
import com.tdam2014.grupo3.flickr.Response;
import com.tdam2014.grupo3.flickr.Transport;

/**
 * Interface for finding Flickr users.
 * 
 * @author Anthony Eden, adapted by Lucas Cunibertti for Flickr Viewer.
 */
public class PeopleInterface {
    
	public static final String METHOD_FIND_BY_USERNAME = "flickr.people.findByUsername";
    public static final String METHOD_GET_INFO = "flickr.people.getInfo";
    
    private String apiKey;
    private Transport transportAPI;

    public PeopleInterface(String apiKey, Transport transportAPI) {
        this.apiKey = apiKey;
        this.transportAPI = transportAPI;
    }

    /**
     * Find a User by the username.
     * This method does not require authentication.
     *
     * @param username The username.
     * @return a People object.
     * @throws IOException
     * @throws FlickrException
     * @throws JSONException 
     */
    public People findByUsername(String username) throws IOException, FlickrException, JSONException {
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("method", METHOD_FIND_BY_USERNAME));
        parameters.add(new Parameter("api_key", apiKey));
        parameters.add(new Parameter("username", username));
        
        Response response = transportAPI.get(transportAPI.getPath(), parameters);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }
        
        JSONObject peopleObject = response.getData();
        return getInfo(peopleObject.getJSONObject("user").getString("nsid"));
    }

    /**
     * Get info about the specified user.
     * This method does not require authentication.
     *
     * @param userId The user NSID.
     * @return a People object.
     * @throws IOException
     * @throws FlickrException
     * @throws JSONException 
     */
    public People getInfo(String userId) throws IOException, FlickrException, JSONException {
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("method", METHOD_GET_INFO));
        parameters.add(new Parameter("user_id", userId));
        parameters.add(new Parameter("api_key", apiKey));
        
        Response response = transportAPI.get(transportAPI.getPath(), parameters);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }
        
        JSONObject peopleObject = response.getData().getJSONObject("person");
        return new People(peopleObject);
    }
}